package com.hmall.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmall.common.client.ItemClient;
import com.hmall.common.client.UserClient;
import com.hmall.item.pojo.Item;
import com.hmall.order.dto.OrderDto;
import com.hmall.order.mapper.OrderDetailMapper;
import com.hmall.order.mapper.OrderLogisticsMapper;
import com.hmall.order.mapper.OrderMapper;
import com.hmall.order.pojo.Order;
import com.hmall.order.pojo.OrderDetail;
import com.hmall.order.pojo.OrderLogistics;
import com.hmall.order.service.IOrderService;
import com.hmall.user.pojo.Address;
import com.hmall.user.util.UserHolder;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;

@Service
public class OrderService extends ServiceImpl<OrderMapper, Order> implements IOrderService {
    @Resource
    private OrderDetailMapper orderDetailMapper;
    @Resource
    private OrderLogisticsMapper orderLogisticsMapper;
    @Resource
    private  OrderService orderService;
    @Resource
    private ItemClient itemClient;
    @Resource
    private UserClient userClient;
    @Resource
    private RabbitTemplate rabbitTemplate;
    /**
     * 创建订单
     * @param requestParams
     * @return
     */
    @Transactional
    @Override
    public Long createOrder(@RequestBody OrderDto requestParams) {
        //地址ID
        //OrderDto orderDto=new OrderDto();
        Long addressId = requestParams.getAddressId();
        //商品ID
        Long itemId = requestParams.getItemId();
        //数量
        Integer num = requestParams.getNum();
        //支付类型
        Integer paymentType = requestParams.getPaymentType();
        Item item = itemClient.findById(itemId);
        //价格
        Long price = item.getPrice();
        //封装
     Order  order=new Order();
    // BeanUtils.copyProperties(orderDto,order);
     //商品金额
        order.setTotalFee(price*num);
        //支付类型
        order.setPaymentType(paymentType);
        order.setUserId(UserHolder.getUser());
        //创建时间
        order.setCreateTime(new Date());
        //支付时间
        order.setPayTime(new Date());
        //发货时间
        order.setConsignTime(new Date());
        //交易完成时间
        order.setEndTime(new Date());
        //交易关闭时间
        order.setCloseTime(new Date());
        //评价时间
        order.setCommentTime(new Date());
        //支付状态
        order.setStatus(1);
        //保存订单
        this.save(order);
        //添加订单明细
        Long id = order.getId();
        OrderDetail orderDetail=new OrderDetail();
        orderDetail.setOrderId(id);
        orderDetail.setItemId(itemId);
        orderDetail.setNum(num);
        orderDetail.setName(item.getName());
        orderDetail.setPrice(price);
        orderDetail.setSpec(item.getSpec());
        orderDetail.setImage(item.getImage());
        orderDetailMapper.insert(orderDetail);
        //获取地址信息
        Address address = userClient.findAddressById(addressId);
        OrderLogistics orderLogistics=new OrderLogistics();
        //属性拷贝
        BeanUtils.copyProperties(address,orderLogistics);
        orderLogistics.setOrderId(order.getId());
        orderLogisticsMapper.insert(orderLogistics);
        try {
            itemClient.updateStock(itemId, num);
        } catch (Exception e) {
            throw  new RuntimeException("库存不足");
        }
        String exchangeName = "exchange.order";
        //routingKey
        String routingKey = "item.delay";
        //消息
        String msg = id.toString();
        Message message = MessageBuilder.withBody(msg.getBytes(StandardCharsets.UTF_8))
                .setDeliveryMode(MessageDeliveryMode.PERSISTENT)
                .setHeader("x-delay", 10000).build();
        //发送消息
        rabbitTemplate.convertAndSend(exchangeName, routingKey, message);
        return order.getId();
    }

    /**
     * 超时取消订单
     */
    @Override
    public void cancelOrder(Long id) {
    /* Order order = orderService.getById(id);
        Integer status = order.getStatus();
        if (status == 1)
        {
            order.setStatus(5);
            order.setUpdateTime(new Date());
            orderService.updateById(order);
        }*/
        //恢复库存
        QueryWrapper<OrderDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id", id);
        List<OrderDetail> orderDetailList = orderDetailMapper.selectList(queryWrapper);
        for (OrderDetail detail : orderDetailList) {
            //根据orderId查询订单详情，得到商品购买数量
            Integer num = detail.getNum();
            //调用item-service，根据商品id、商品数量恢复库存
            itemClient.updateStock(detail.getItemId(), num * -1);
        }
    }

    /**
     * 订单支付
     * @param paytype
     * @param oid
     * @return
     */
    //@Override
   /* public Integer pay(Long paytype, Long oid) {
        Order order = orderService.getById(oid);
        return order.getStatus();
    }*/
}
